package com.gitee.cui.basic.create;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 创建线程的第二种方式，实现Runnable接口
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/9 16:09
 **/
@Slf4j
public class CreateThread2 {

    private static final int TURN = 5;

    static int threadNo = 0;

    static class RunTarget implements Runnable {

        @Override
        public void run() {
            for (int i = 1; i < TURN; i++) {
                log.info(ThreadUtil.getCurThreadName() + "，轮次：{}", i);
            }
            log.info("{} 运行结束", ThreadUtil.getCurThreadName());
        }
    }

    public static void main(String[] args) {
        runnbaleFunction();

        innerClassFunction();

        lambdaFunction();
    }

    /**
     * lambda方式实现
     */
    private static void lambdaFunction() {
        Thread thread = null;
        for (int i = 0; i < 2; i++) {
            thread = new Thread(() -> {
                for (int i1 = 1; i1 < TURN; i1++) {
                    log.info(ThreadUtil.getCurThreadName() + "，轮次：{}", i1);
                }
                log.info("{} 运行结束", ThreadUtil.getCurThreadName());
            }, "RunnableThread-" + threadNo++);
            thread.start();
        }
    }

    /**
     * 匿名内部类方式实现
     */
    private static void innerClassFunction() {
        Thread thread = null;
        for (int i = 0; i < 2; i++) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 1; i < TURN; i++) {
                        log.info(ThreadUtil.getCurThreadName() + "，轮次：{}", i);
                    }
                    log.info("{} 运行结束", ThreadUtil.getCurThreadName());
                }
            }, "RunnableThread-" + threadNo++);
            thread.start();
        }
    }

    /**
     * 通过实现Runnable接口方式调用
     */
    private static void runnbaleFunction() {
        Thread thread = null;
        for (int i = 0; i < 2; i++) {
            Runnable target = new RunTarget();
            thread = new Thread(target, "RunnableThread-" + threadNo++);
            thread.start();
        }
    }
}
